<?php

declare(strict_types=1);

namespace App\Amqp\Consumer;

use App\Service\OrderService\OrderMessageService;
use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Message\ConsumerMessage;
use Hyperf\Amqp\Result;
use PhpAmqpLib\Message\AMQPMessage;
use Hyperf\Amqp\Message\Type;


/**
 * qos (prefetch_size,prefetch_count,global)
 * 发送
 * @Consumer(exchange="ORDER_MESSAGE_EVENT_MESSAGE", routingKey="ORDER_MESSAGE_EVENT_MESSAGE", queue="ORDER_MESSAGE_EVENT_MESSAGE", nums=1)
 */
class OrderMessageConsumer extends ConsumerMessage
{
    protected $type = Type::DIRECT;//直连模式
    protected $qos  = [
        'prefetch_count'    => 10
    ];

    public function consumeMessage($data, AMQPMessage $message): string
    {
        try {
            OrderMessageService::instance()->syncMessage($data);
            return Result::ACK;
        } catch ( \Throwable $t ) {
            echo $t->getMessage().PHP_EOL;
            logger('error','OrderMessageError')->info($t->getMessage());
            sleep(3);//休眠3秒之后，重回队列
            return Result::REQUEUE;
        }
    }
    
    /**
     * 设置是否自启动
     */
    public function isEnable() : bool
    {
        $isDisAable = env('AMQP_ORDER_MESSAGE_EVENT_MESSAGE_CONSUMER_DISABLE');
        return $isDisAable ? false : true ;
    }
}